import cv2
import tkinter as tk
from PIL import Image, ImageTk

# 加载人脸和眼睛的级联分类器
face_cascade = cv2.CascadeClassifier('D:\\OpenCV\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('D:\\OpenCV\\build\\etc\\haarcascades\\haarcascade_eye.xml')

# 全局变量用于控制摄像头状态
is_camera_on = False
cap = None

def start_camera():
    global is_camera_on, cap
    if not is_camera_on:
        cap = cv2.VideoCapture(0)
        is_camera_on = True
        update_frame()

def stop_camera():
    global is_camera_on, cap
    if is_camera_on:
        cap.release()
        is_camera_on = False
        canvas.delete("all")

def update_frame():
    global is_camera_on, cap
    if is_camera_on:
        ret, frame = cap.read()
        if ret:
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            faces = face_cascade.detectMultiScale(gray, 1.3, 5)
            for (x, y, w, h) in faces:
                cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
                roi_gray = gray[y:y + h, x:x + w]
                roi_color = frame[y:y + h, x:x + w]
                eyes = eye_cascade.detectMultiScale(roi_gray)
                for (ex, ey, ew, eh) in eyes:
                    cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)
            # 将OpenCV图像转换为PIL图像，再转换为Tkinter PhotoImage
            img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = Image.fromarray(img)
            img = ImageTk.PhotoImage(image=img)
            canvas.create_image(0, 0, anchor=tk.NW, image=img)
            canvas.image = img  # 保存对图像的引用，防止被垃圾回收
        root.after(10, update_frame)  # 每隔10毫秒更新一次画面

root = tk.Tk()
root.title("人脸识别界面")
root.geometry("500x500")

# 创建一个按钮来启动和停止摄像头
start_button = tk.Button(root, text="启动摄像头", command=start_camera)
start_button.pack()
stop_button = tk.Button(root, text="停止摄像头", command=stop_camera)
stop_button.pack()

# 创建一个画布用于显示摄像头画面
canvas = tk.Canvas(root, width=640, height=480)
canvas.pack()

root.mainloop()